package top.lenjon.lib.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.lenjon.lib.annotation.MailSign;
import top.lenjon.lib.entity.UserDetail;
import top.lenjon.lib.model.MailModel;
import top.lenjon.lib.model.ResponseModel;
import top.lenjon.lib.service.IBookService;
import top.lenjon.lib.service.LoginService;
import top.lenjon.lib.service.MailService;
import top.lenjon.lib.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * @Author whz
 * @Date 2020/11/10 11:17
 **/
@Aspect
@Component
public class MailAspect {

    @Autowired
    MailService mailService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    LoginService loginService;
    @Autowired
    IBookService bookService;

    private final static String REGISTER_MESSAGE = "注册成功，请在下方确认激活账户,30分钟内有效";
    private final static String RENEW_MESSAGE="续借成功:";
    private final static String RETURN_MESSAGE="归还成功:";

    @Pointcut("@annotation(top.lenjon.lib.annotation.MailSign)")
    public void mailmq() {

    }

    @AfterReturning(value = "mailmq()&& @annotation(mailSign)", returning = "responseValue")
    public void sendMail(JoinPoint joinPoint, Object responseValue, MailSign mailSign) {
        HttpServletRequest request=((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        UserDetail userDetail=new UserDetail();
        ResponseModel responseModel = (ResponseModel) responseValue;
        System.out.println(joinPoint.getTarget().toString());
        MailModel mailModel=null;
        int bookId;
        String username;
        String message;
        if (responseModel.getCode() == 200) {
            switch (mailSign.value()) {
                case "续借":
                     bookId=(int)getArgs(joinPoint,"bookId");
                     username=getArgs(joinPoint,"username").toString();
                    userDetail.setUsername(username);
                    userDetail.setNickname(username);
                    String bookName=bookService.getById(bookId).getTitle();
                     message=RENEW_MESSAGE+bookName;
                    mailModel=setMailModel(message,userDetail,null);
                    break;
                case "归还":
                     bookId=(int)getArgs(joinPoint,"bookId");
                     username=getArgs(joinPoint,"username").toString();
                    userDetail.setUsername(username);
                    userDetail.setNickname(username);
                    String bookName1=bookService.getById(bookId).getTitle();
                    message=RETURN_MESSAGE+bookName1;
                    mailModel=setMailModel(message,userDetail,null);
                case "逾期":


            }
            Optional.ofNullable(mailModel).ifPresent(mailService::sendHtmlMail);
        }
    }

    @Pointcut("execution(public * top.lenjon.lib.controller.RegisterController.registerUser(..))")
    public void register() {

    }

    @AfterReturning(value = "register()", returning = "responseValue")
    public void register(JoinPoint joinPoint, Object responseValue) {
        Object[] args = joinPoint.getArgs();
        UserDetail userDetail = (UserDetail) args[0];
        ResponseModel responseModel = (ResponseModel) responseValue;
        if (responseModel.getCode() == 200) {
            String uuid = UUID.randomUUID().toString();
            redisUtil.set(uuid, userDetail,30*60*60);
            //给异步线程的新RequestContextHolder传递信息
            RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
            mailService.sendRegisterMail(setMailModel(REGISTER_MESSAGE, userDetail, uuid));
        }
    }

    public Object getArgs(JoinPoint joinPoint,String param){
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature=(MethodSignature)joinPoint.getSignature();
        String[] paramNames=methodSignature.getParameterNames();
        for(int i=0;i<paramNames.length;i++){
            if(paramNames[i].equals(param)){
                return args[i];
            }
        }
        return null;
    }
    public MailModel setMailModel(String message, UserDetail userDetail, String uuid) {
        MailModel mailModel = new MailModel();
        mailModel.setEmail(userDetail.getUsername());
        mailModel.setMessage(message);
        mailModel.setNickname(userDetail.getNickname());
//        mailModel.setId(userDetail.getId());
        if (uuid != null) {
            mailModel.setUuid(uuid);
        }
        return mailModel;
    }
}
